package com.asd.system.service.Impl;

import com.asd.common.Result;
import com.asd.common.constant.CacheConstant;
import com.asd.common.constant.CommonConstant;
import com.asd.system.entity.User;
import com.asd.system.mapper.OrganizationMapper;
import com.asd.system.mapper.RoleMapper;
import com.asd.system.mapper.UserMapper;
import com.asd.system.service.IUserService;
import com.asd.system.entity.vo.UserVO;
import com.asd.util.PasswordUtil;
import com.asd.util.oConvertUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author
 * @createtime 2021-09-13 14:20
 * @description
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Override
    public List<User> selectUserPage(Page<User> page) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //  判断年龄大于20岁的，这里用的是mybatis-plus的条件构造器
//        queryWrapper.gt("age",20);
        /**
         *    加上false就不查询总记录数啦,如果不需要的话可以加上false，这样就会少一条sql语句
         *   Page<Student> page = new Page<>(current,size,false);
         */
//        Page<Information> page1 = new Page<>();
        //   queryWrapper  可以为null  不进行条件判断
        //  返回list 调用  selectPage
        IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);


//        System.out.println("总页数" + userIPage.getPages());
//        System.out.println("总记录数" + userIPage.getTotal());
        //getRecords()分页对象记录列表
        List<User> records = userIPage.getRecords();
        return records;
    }

    @Override
    public Result<?> changePassword(User user) {
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String password = user.getPassWord();
        String passwordEncode = PasswordUtil.encrypt(user.getUserName(), password, salt);
        user.setPassWord(passwordEncode);
        this.userMapper.updateById(user);
        return Result.ok("密码修改成功!");
    }

    @Override
    public User findToName(String username) {
        User user = userMapper.findToName(username);
        return user;
    }

    @Override
    public Result checkUserIsEffective(User user) {
        Result<?> result = new Result<Object>();
        //情况1：根据用户信息查询，该用户不存在
        if (user == null) {
            result.error500("该用户不存在，请注册");
            return result;
        }
        //情况2：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(user.getIsEnable())) {
            result.error500("该用户已冻结");
            return result;
        }

        return result;
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchUsers(String userIds) {
        //1.删除用户
        this.removeByIds(Arrays.asList(userIds.split(",")));
        return false;
    }

    @Override
    public List<UserVO> getByOrgId(String orgId) {

        ArrayList<UserVO> list = new ArrayList<>();

        List<User> userList = userMapper.getByOrgId(orgId);

        for (int i = 0; i < userList.size(); i++) {

            UserVO userVO = new UserVO();

            User user = userList.get(i);
            //获取角色名称
            String roleName = roleMapper.selectById(user.getRoleId()).getName();
            //获取组织名称
            String orgName = organizationMapper.selectById(user.getOrgId()).getName();
            userVO.setId(user.getId());
            userVO.setIsEnable(user.getIsEnable());
            userVO.setNickname(user.getNickname());
            userVO.setUserName(user.getUserName());
            userVO.setNote(user.getNote());
            userVO.setRoleId(user.getRoleId());
            userVO.setOrgId(user.getOrgId());
            userVO.setRoleName(roleName);
            userVO.setOrgName(orgName);

            list.add(userVO);
        }
        return list;
    }

    @Override
    public boolean updateUserBasicInfo(String id, String nickname, String note) {

        userMapper.updateUserBasicInfo(id, nickname, note);

        return true;
    }


}
